package com.atguigu.gmall.cart.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.feign.GmallPmsClient;
import com.atguigu.gmall.cart.mapper.CartMapper;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.pms.entity.SkuEntity;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class CartLinstener {

    @Autowired
    GmallPmsClient gmallPmsClient;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    private static final String PRICE_PREFIX = "cart:prcice:";
    private static final String KEY_PREFIX = "cart:info:";


    /*
    缓存商品变动的价格
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "CART-UPDATE"),
            exchange = @Exchange(value = "PMS_SPU_EXCHANGE",type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = "cart-update"
    ))
    public void message(Channel channel, Message message,Long spuId) throws IOException {
        if (spuId==null){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false );
        }
        //根据spuId查询sku商品信息
        ResponseVo<List<SkuEntity>> responseVo = gmallPmsClient.querySkusBySpuId(spuId);
        List<SkuEntity> skuEntities = responseVo.getData();
        if(CollectionUtils.isEmpty(skuEntities)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false );
        }
        try {
            skuEntities.forEach(item->{
                redisTemplate.opsForValue().setIfPresent(PRICE_PREFIX+item.getId().toString(),item.getPrice().toString());
            });
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

    /*
    订单提交成功后 删除购物车中对应的数据
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "CART-DELETE"),
            exchange = @Exchange(value = "ORDER_EXCHANGE",type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = "cart.del"
    ))
    public void cartDel(Map map,Channel channel,Message message) throws IOException {
        if (CollectionUtils.isEmpty(map)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        Long userId = (Long) map.get("userId");
        List<String> skuIds = JSON.parseArray(map.get("skuIds").toString(), String.class);
        if (userId==null||CollectionUtils.isEmpty(skuIds)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        //删除订单商品
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        boundHashOps.delete(skuIds.toArray());
        this.cartMapper.delete(new UpdateWrapper<Cart>().eq("user_id", userId).in("sku_id", skuIds));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
